<template>
    <div id="myChart" class="chart"></div>
</template>

<script>
import echarts from 'echarts'
export default {
  name: 'typeEcharts',
  data () {
    return {
      typeOne: [],
      baseTitle: [], // 横坐标标题
      twoCount: [] // 一级类别对应的二级类别数量
    }
  },
  mounted () {
    this.findOneLevels()
  },
  methods: {
    drawLine (title, count) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(document.getElementById('myChart'))
      // 绘制图表
      myChart.setOption({
        title: { text: '类别统计' },
        tooltip: {},
        xAxis: {
          data: title
        },
        yAxis: {},
        series: [{
          name: '二级类别',
          type: 'bar',
          data: count
        }]
      })
    },
    // 查询所有一级商品类别与二级商品类别
    findOneLevels () {
      this.$axios({
        url: 'types/findOneLevels',
        method: 'get'
      }).then(res => {
        if (res.data.code === 200) {
          this.typeOne = res.data.list
          this.typeOne.forEach(item => {
            this.$axios({
              url: 'types/findTwoLevels/' + item.tId,
              method: 'get'
            }).then(res => {
              if (res.data.code === 200) {
                // 加入二级类别
                this.$set(item, 'child', res.data.list)
                this.baseTitle.push(item.tName)
                this.twoCount.push(item.child.length)
                this.drawLine(this.baseTitle, this.twoCount)
              }
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.chart {
    width: 100%;
    height: 300px;
}
</style>
